#include "keymanager.h"
#include "certificatemanager.h"
#include "utils/TimeOperation.h"

bool keyManager::initializeKeys()
{
    //首先先判断公钥证书是否过期了失效了,如果失效了就往下走，如果没失效，直接提取公私钥就行
    EVP_PKEY *pubKey = nullptr;
    if (!certManger.ExtractVerifyPKCertIsValid(&pubKey, CLIENT_CERT_FILEPATH)) {
        std::cerr << "Fail to ExtractVerifyPKCertIsValid!" << std::endl;
        return false;
    }
    evp_pubKey.reset(pubKey, EVP_PKEY_Deleter);

    //然后就是检查私钥
    EVP_PKEY *priKey = nullptr;
    if (!certManger.Extract_and_verify_privKey_is_valid(&priKey, CLIENT_PRIKEY_FILEPATH)) {
        std::cerr << "Fail to Extract and verify privKey!" << std::endl;
        return false;
    }
    evp_prikey.reset(priKey, EVP_PKEY_Deleter);

    BIGNUM *bn = m_ecc.EVPPriKey_Convert_BN(priKey);
    if (!bn) {
        std::cerr << "Fail to EVPPriKey_Convert_BN!" << std::endl;
    }

    bn_priKey.reset(bn, BnDeleter);

    EC_POINT *ec_point = m_ecc.EVP_PKEY_PubKey_Convert_EC(pubKey);
    if (!ec_point) {
        std::cerr << "Fail to EVP_PKEY_PubKey_Convert_EC!" << std::endl;
    }

    ec_point_pubKey.reset(ec_point, ECPointDeleter);

    return true;
}

void keyManager::setKeys(std::shared_ptr<BIGNUM> bnPrikey,
                         std::shared_ptr<EC_POINT> ec_pubKey,
                         std::shared_ptr<EVP_PKEY> evp_SK,
                         std::shared_ptr<EVP_PKEY> evp_PK)
{
    bn_priKey = bnPrikey;
    ec_point_pubKey = ec_pubKey;
    evp_prikey = evp_SK;
    evp_pubKey = evp_PK;
}

std::shared_ptr<EC_POINT> keyManager::getPubkey()
{
    return ec_point_pubKey;
}

std::shared_ptr<BIGNUM> keyManager::getPriKey()
{
    return bn_priKey;
}

std::shared_ptr<unsigned char> keyManager::getSalt()
{
    return m_salt;
}

std::shared_ptr<EC_POINT> keyManager::getCAPubKey()
{
    return ca_ecpoint_pubKey;
}

void keyManager::setSymmKey(const std::vector<unsigned char> &symmKey)
{
    SymmKeyIsSeted = true;
    symmKey_vector = symmKey;
}

bool keyManager::getSymmKeyIsSeted()
{
    return SymmKeyIsSeted;
}

std::vector<unsigned char> keyManager::getSymmKey()
{
    return symmKey_vector;
}

keyManager::keyManager()
    : SymmKeyIsSeted(false)
{
    //提取CA的公钥
    EVP_PKEY *CA_public = nullptr;
    if (!CertificateManager::instance().loadCACertificate(&CA_public, CA_CERT_FILEPATH)) {
        qDebug() << "CA cert is error!";
        throw std::runtime_error("CA cert is error!");
    }

    //然后就是将CA的公钥转换为EC_POINT类型
    EC_POINT *ca_ecpoint = m_ecc.EVP_PKEY_PubKey_Convert_EC(CA_public);
    if (!ca_ecpoint) {
        EVP_PKEY_free(CA_public);
        throw std::runtime_error("EVP_PKEY_PubKey_Convert_EC is error!");
    }
    EVP_PKEY_free(CA_public);
    ca_ecpoint_pubKey.reset(ca_ecpoint, ECPointDeleter);

    //还需要初始化盐值
    //产生盐值
    unsigned char *salt = generate_salt(16);
    m_salt.reset(salt, UCharOpenSSlDeleter);
}
